package com.hotacorp.opencloud.userservice.service.impl;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hotacorp.opencloud.userservice.dao.SysUserRoleDao;
import com.hotacorp.opencloud.userservice.entity.SysUserRoleEntity;
import com.hotacorp.opencloud.userservice.service.SysUserRoleService;

/**
 * 用户角色管理接口实现
 * @author lwg
 *
 */
@Service("sysUserRoleService")
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleDao, SysUserRoleEntity> implements SysUserRoleService {

	@Override
	public List<Long> queryRoleIdList(Long userId, Long tenantid) {
		List<SysUserRoleEntity> rrrEntities = baseMapper.selectList((new QueryWrapper<SysUserRoleEntity>()).eq("tenantid", tenantid).eq("user_id", userId));
		Set<Long> yyyy = rrrEntities.stream().map(entity->{return entity.getRoleId();}).collect(Collectors.toSet());
		return yyyy.stream().collect(Collectors.toList());
	}

	@Override
	public void saveOrUpdate(Long userId, List<Long> roleIdList, Long tenantid) {
		//先删除用户与角色关系
		this.remove((new QueryWrapper<SysUserRoleEntity>()).eq("tenantid", tenantid).eq("user_id", userId));

		if(roleIdList == null || roleIdList.size() == 0){
			return ;
		}

		//保存用户与角色关系
		for(Long roleId : roleIdList){
			SysUserRoleEntity sysUserRoleEntity = new SysUserRoleEntity();
			sysUserRoleEntity.setUserId(userId);
			sysUserRoleEntity.setRoleId(roleId);
			sysUserRoleEntity.setTenantid(tenantid);

			this.save(sysUserRoleEntity);
		}
	}

	@Override
	public void removeUsers(List<Long> userIds, Long tenantid) {
		QueryWrapper<SysUserRoleEntity> wrap1 = new QueryWrapper<SysUserRoleEntity>();
		wrap1.eq("tenantid", tenantid);
		wrap1.in("user_id", userIds);
		baseMapper.delete(wrap1);
	}

	@Override
	public void removeRoles(List<Long> roleIds, Long tenantid) {
		QueryWrapper<SysUserRoleEntity> wrap1 = new QueryWrapper<SysUserRoleEntity>();
		wrap1.eq("tenantid", tenantid);
		wrap1.in("role_id", roleIds);
		baseMapper.delete(wrap1);
	}

}